package com.lzb.web.intercepter;

import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lzb.cache.SessionCached;
import com.lzb.model.MngUserModel;

public class LoginInterceptor implements HandlerInterceptor {

	@Resource(name = SessionCached.BEAN_PACKAGE_NAME)
	private SessionCached cachedSession;
	
	@Value("${session.timeout.seconds}")
	private int sessionTimeoutSeconds;
	
	public LoginInterceptor() {}
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//请求路径
		String url = request.getRequestURI();
		int position = StringUtils.lastIndexOf(url, "/");
		String path = url.substring(position + 1);
		HttpSession session = request.getSession();
		String sessionId = session.getId();
		MngUserModel user = cachedSession.get(sessionId);
		if(StringUtils.isBlank(path) || StringUtils.startsWithIgnoreCase(path, "doNotNeedSecurity") || "login.do".equalsIgnoreCase(path)) {
			return true;
		} else {
			if(user == null) {
				//拦截异步请求
				if (request.getHeader("X-Requested-With") != null
						&& request.getHeader("X-Requested-With").equalsIgnoreCase(     
						"XMLHttpRequest")) {  
						response.setCharacterEncoding("text/html;charset=utf-8");
						response.setContentType("text/html;charset=utf-8");
						PrintWriter pw = response.getWriter();
						pw.write("sessionTimeOut");
						pw.flush();
						pw.close();
						return false;
				}
				response.sendRedirect(request.getContextPath()+"/resources/global/jsp/noSession.jsp");  
				return false;
			} else {
				//更新过期时间
				cachedSession.expire(session.getId(), sessionTimeoutSeconds);
			}
			return true;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
